import 'package:flutter/material.dart';

class Circle extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CircleState();
  }
}

class _CircleState extends State<Circle> with SingleTickerProviderStateMixin {

  AnimationController _controller;
  Animation<double> _withHeight;

  @override
  void initState() {
    super.initState();

    // 时长
    _controller = AnimationController(
      duration: Duration(seconds: 3),
      vsync: this,
    );

    // 动画曲线
    final _curve = CurvedAnimation(parent: _controller, curve: Curves.easeIn);

    // 图片宽高从0变到300
    _withHeight = Tween(begin: 0.0, end: 300.0).animate(_curve);

    // 状态侦听
    _withHeight.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        // 动画执行结束时反向执行动画
        _controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        // 动画反向执行结束时正向执行动画
        _controller.forward();
      }
    });

    // 启动动画(正向执行)
    _controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('循环动画的例子'),
      ),
      body: SizedBoxAnimation(
          child: Image.asset('image/icon-60.png', fit: BoxFit.fill,),
          animation: _withHeight),
    );
  }

  @override
  void dispose() {
    // 路由销毁时需要释放动画资源
    _controller.dispose();

    super.dispose();
  }
}

class SizedBoxAnimation extends StatelessWidget {
  SizedBoxAnimation({@required this.child, @required this.animation});

  final Widget child;
  final Animation<double> animation;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedBuilder(
        child: child,
        animation: animation,
        builder: (BuildContext context, Widget child) {
          return SizedBox(
            width: animation.value, 
            height: animation.value,
            child: child,
          );
        },
      ),
    );
  }
}